package com.osfw.dbadminer.controller.connect;

import com.osfw.dbadminer.entity.connect.DbaConnect;
import com.osfw.dbadminer.service.connect.IDbaConnectService;
import com.osfw.framework.annotation.Log;
import com.osfw.framework.core.controller.BaseController;
import com.osfw.framework.core.domain.Ztree;
import com.osfw.framework.enums.BusinessType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 数据库连接
 */
@Controller
@RequestMapping("/osfw/dbadminer/connect")
public class DbaConnectController extends BaseController {
    private String prefix = "osfw/dbadminer/connect";

    @Autowired
    private IDbaConnectService connectService;


    @Log(title = "查询数据库连接", businessType = BusinessType.GRANT)
    @GetMapping("/list")
    @ResponseBody
    public List<DbaConnect> list() {
        List<DbaConnect> connects = connectService.getConnects();
        return connects;
    }

    @GetMapping("/add")
    public String add(ModelMap mmap) {
        return prefix + "/add";
    }

    @Log(title = "新增数据库连接", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public boolean add(@RequestBody DbaConnect connect, HttpServletRequest request) {
        connect.setCreateAt(new Date());
        connect.setCreateIp(request.getRemoteAddr());
        return connectService.save(connect);
    }

    @GetMapping("/edit/{id}")
    public String edit(ModelMap mmap, Long id) {
        DbaConnect connect = connectService.getById(id);
        mmap.put("connect", connect);
        return prefix + "/edit";
    }


    @Log(title = "编辑数据库连接", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public boolean edit(@RequestBody DbaConnect connect, HttpServletRequest request) {
        connect.setUpdateAt(new Date());
        connect.setUpdateIp(request.getRemoteAddr());
        return connectService.updateById(connect);
    }

    @Log(title = "删除数据库连接", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{id}")
    @ResponseBody
    public boolean remove(@PathVariable Integer id) {
        return connectService.removeById(id);
    }

    /**
     * 加载所有数据库列表树
     */
    @GetMapping("/databaseTreeImmediateChild")
    @ResponseBody
    public List<Ztree> databaseTreeImmediateChild(Long parentId) {
        List<Ztree> ztrees = connectService.databaseTreeImmediateChild(parentId, getSysUser());
        return ztrees;
    }
}
